package services.kingdee

import models.outstock._

import java.sql.Timestamp
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import javax.inject.{Inject, Singleton}
import play.api.Logging
import play.api.libs.json.{JsArray, JsObject, JsValue, Json}
import services.intermediate.SendOutStockSum
import utiliy.OutFilterConfig
import scala.concurrent.{ExecutionContext, Future}

class ReceiveService @Inject()(
                                osrRep: OutStockRevRepository,
                                kdPost: KingdeePostV1,
                                kdPost2: KingdeePostV2,
                                ofc: OutFilterConfig,
                                sendoss: SendOutStockSum
                              )(implicit exec: ExecutionContext)
  extends Logging {
  val errorInfo = (x: String, y: String) =>
    s"""{"Result":{"ResponseStatus":{"ErrorCode":500,"IsSuccess":false,
       |"Errors":[{"Message":"$x.errorInfo:$y"}],
       |"SuccessEntitys":[],"SuccessMessages":[],
       |"MsgCode":11},"Id":"","Number":"","NeedReturnData":[{}]}}""".stripMargin
  val dtformat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
  var dcId: String = ""

  def setDCId(dcId: String) = {
    this.dcId = dcId
    this
  }

  //,#查看表单数据接口
  def webapiView(argJson: JsValue): Future[String] = {
    val parameters = if ((argJson \ "data").asOpt[JsValue].isEmpty) {
      val p = (argJson \ "parameters").as[JsArray].value
      (p.head.as[String], p.last)
    } else {
      ((argJson \ "formid").as[String], (argJson \ "data").as[JsValue])
    }
    logger.debug(s"webapiView formid=${parameters._1};parameters = ${parameters._2.toString}")
    kdPost2.setKdAppConfig(dcId).view(parameters._1, parameters._2)
  }

  //,#保存表单数据接口
  def webapiSave(argJson: JsValue): Future[String] = {
    val parameters = if ((argJson \ "data").asOpt[JsValue].isEmpty) {
      val p = (argJson \ "parameters").as[JsArray].value
      (p.head.as[String], p.last)
    } else {
      ((argJson \ "formid").as[String], (argJson \ "data").as[JsValue])
    }
    logger.debug(s"webapiSave formid=${parameters._1};parameters = ${parameters._2.toString}")
    kdPost2.setKdAppConfig(dcId).save(parameters._1, parameters._2)
  }

  //,#批量保存表单数据接口
  def webapiBatchSave(argJson: JsValue): Future[String] = {
    val parameters = if ((argJson \ "data").asOpt[JsValue].isEmpty) {
      val p = (argJson \ "parameters").as[JsArray].value
      (p.head.as[String], p.last)
    } else {
      ((argJson \ "formid").as[String], (argJson \ "data").as[JsValue])
    }
    logger.debug(s"webapiBatchSave formid=${parameters._1};parameters = ${parameters._2.toString}")
    kdPost2.setKdAppConfig(dcId).batchSave(parameters._1, parameters._2)
  }

  //,#提交表单数据接口
  def webapiSubmit(argJson: JsValue): Future[String] = {
    val parameters = if ((argJson \ "data").asOpt[JsValue].isEmpty) {
      val p = (argJson \ "parameters").as[JsArray].value
      (p.head.as[String], p.last)
    } else {
      ((argJson \ "formid").as[String], (argJson \ "data").as[JsValue])
    }
    logger.debug(s"webapiSubmit formid=${parameters._1};parameters = ${parameters._2.toString}")
    kdPost2.setKdAppConfig(dcId).submit(parameters._1, parameters._2)
  }

  //,#审核表单数据接口
  def webapiAudit(argJson: JsValue): Future[String] = {
    val parameters = if ((argJson \ "data").asOpt[JsValue].isEmpty) {
      val p = (argJson \ "parameters").as[JsArray].value
      (p.head.as[String], p.last)
    } else {
      ((argJson \ "formid").as[String], (argJson \ "data").as[JsValue])
    }
    logger.debug(s"webapiAudit formid=${parameters._1};parameters = ${parameters._2.toString}")
    kdPost2.setKdAppConfig(dcId).audit(parameters._1, parameters._2)
  }

  //,#反审核表单数据接口
  def webapiUnAudit(argJson: JsValue): Future[String] = {
    val parameters = if ((argJson \ "data").asOpt[JsValue].isEmpty) {
      val p = (argJson \ "parameters").as[JsArray].value
      (p.head.as[String], p.last)
    } else {
      ((argJson \ "formid").as[String], (argJson \ "data").as[JsValue])
    }
    logger.debug(s"webapiUnAudit formid=${parameters._1};parameters = ${parameters._2.toString}")
    kdPost2.setKdAppConfig(dcId).unAudit(parameters._1, parameters._2)
  }

  //,#删除表单数据接口
  def webapiDelete(argJson: JsValue): Future[String] = {
    val parameters = if ((argJson \ "data").asOpt[JsValue].isEmpty) {
      val p = (argJson \ "parameters").as[JsArray].value
      (p.head.as[String], p.last)
    } else {
      ((argJson \ "formid").as[String], (argJson \ "data").as[JsValue])
    }
    logger.debug(s"webapiDelete formid=${parameters._1};parameters = ${parameters._2.toString}")
    kdPost2.setKdAppConfig(dcId).delete(parameters._1, parameters._2)
  }

  //,#表单数据查询接口
  def webapiQuery(argJson: JsValue): Future[String] = {
    val parameters = if ((argJson \ "data").asOpt[JsValue].isEmpty) {
      val p = (argJson \ "parameters").as[JsArray].value
      p.last
    } else {
      (argJson \ "data").as[JsValue]
    }
    logger.debug(s"webapiQuery parameters = ${parameters.toString}")
    kdPost2.setKdAppConfig(dcId).executeBillQuery(parameters)
  }

  //,#状态转换
  def webapiStatusConvert(argJson: JsValue): Future[String] = Future(errorInfo("webapiStatusConvert", s"${argJson.toString()}"))

  // 执行操作
  def webapiExcuteOperation(argJson: JsValue): Future[String] = {
    val parameters = if ((argJson \ "data").asOpt[JsValue].isEmpty) {
      val p = (argJson \ "parameters").as[JsArray].value
      (p.head.as[String], p(1).as[String], p.last)
    } else {
      ((argJson \ "formid").as[String], (argJson \ "opNumber").as[String], (argJson \ "data").as[JsValue])
    }
    logger.debug(s"webapiExcuteOperation formid=${parameters._1};opNumber=${parameters._2},parameters = ${parameters._3.toString}")
    kdPost2.setKdAppConfig(dcId).excuteOperation(parameters._1, parameters._2, parameters._3)
  }

  // 管易.发货单》》销售出库单
  def webapiOutStockService(argJson: JsValue): Future[String] = {
    try {
      val dataModel = if ((argJson \ "data").asOpt[JsValue].isEmpty) {
        val p = (argJson \ "parameters").as[JsArray].value.head
        if (p.isInstanceOf[JsObject]) {
          p("Model")
        } else {
          Json.parse(p.as[String])("Model")
        }
      } else {
        (argJson \ "data").as[JsValue]
      }
      logger.debug(s"webapiOutStockService parameters = ${dataModel.toString}")
      val fEntity = Json.obj(
        "FEntity" ->
          Json.toJson(
            dataModel("FEntity").as[JsArray].value.map(
              v =>
                Json.obj(
                  "FAllAmount" -> v("FAllAmount"),
                  "FAmount" -> v("FAmount"),
                  "FDiscount" -> v("FDiscount"),
                  "FFeeAmount" -> v("FFeeAmount"),
                  "FGYEntryID" -> v("FGYEntryID"),
                  "FIsFree" -> v("FIsFree"),
                  "FMaterialNumber" -> v("FMaterialNumber"),
                  "FORDERBILLNO" -> v("FORDERBILLNO"),
                  "FPrice" -> v("FPrice"),
                  "FQty" -> v("FQty"),
                  "FServiceAmount" -> v("FServiceAmount")
                )
            )
          )
      )
      val req = OutStockRecive(
        //osrFEntity = true,
        osrFDate = Timestamp.valueOf(LocalDateTime.parse(dataModel("FDate").as[String], dtformat)),
        osrFGYBillNo = dataModel("FGYBillNo").as[String], //"SDO"+ nowTime.getMillis,
        osrFShopNumber = dataModel("FShopNumber").as[String], //"SHOP00101",
        osrFStockNumber = dataModel("FStockNumber").as[String], //"ST0002",
        osrFEntityInfo = Option(fEntity.toString) //Option(new javax.sql.rowset.serial.SerialClob("""{"sssssss"}""".toCharArray))
      )
      osrRep.insertOSR(req).map {
        resultId =>
          Json.obj(
            "Result" -> Json.obj(
              "Number" -> s"XSCKD${resultId.getOrElse(0)}",
              "ResponseStatus" -> Json.obj(
                "IsSuccess" -> true,
                "Errors" -> Json.arr(),
                "MsgCode" -> 0,
                "SuccessEntitys" -> Json.arr(
                  Json.obj("Number" -> s"XSCKD${resultId.getOrElse(0)}", "Id" -> resultId, "DIndex" -> 0)
                ),
                "SuccessMessages" -> Json.arr()
              ),
              "Id" -> resultId,
              "NeedReturnData" -> Json.arr(Json.obj())
            )
          ).toString()
      }
      //      }
    } catch {
      case e: Exception => logger.error("webapiOutStockService", e); Future(errorInfo("webapiOutStockService.exception", s"${argJson.toString()}"))
    }

  }

  // 管易.退换货单》》销售退货单 k3cloud 7.3
  def webapiReturnStockService1(argJson: JsValue): Future[String] = {
    //val dataModel = argJson(0)("Model")
    import play.api.libs.json._
    import play.api.libs.json.Reads._
    /**
     * var["FExpiryDate"] = "1971-01-01 00:00:00"
     * var["FLotNumber"] = 2018
     * var["FProduceDate"] = "1971-01-01 00:00:00"
     *
     */
    try {
      val dataModel = if ((argJson \ "data").asOpt[JsValue].isEmpty) {
        val p = (argJson \ "parameters").as[JsArray].value.head
        if (p.isInstanceOf[JsObject]) {
          p("Model")
        } else {
          Json.parse(p.as[String])("Model")
        }
      } else {
        (argJson \ "data").as[JsValue]
      }
      logger.debug(s"webapiReturnStockService7.3 parameters = ${dataModel.toString}")
      val shop = (dataModel \ "Model" \ "FShopNumber").get.as[String]
      val stock = (dataModel \ "Model" \ "FStockNumber").get.as[String]
      val gyId = (dataModel \ "Model" \ "FGYBillNo").get.as[String]

      /**
       * {"Result":{"ResponseStatus":{"IsSuccess":true,"Errors":[],"SuccessEntitys":
       * [{"Id":462180,"Number":"XSTHD2108122202","DIndex":0}],"SuccessMessages":[],
       * "MsgCode":0},"Id":462180,"Number":"XSTHD2108122202","NeedReturnData":[{}]}}
       *
       * {"Result":{"ResponseStatus":{"ErrorCode":500,"IsSuccess":false,"Errors":
       * [{"FieldName":"FThirdBillNo","Message":"管易对接销售退货单单据分录行第三方单据编码存在重复",
       * "DIndex":0}],"SuccessEntitys":[],"SuccessMessages":[],"MsgCode":0},
       * "Id":"","NeedReturnData":[{}]}}
       *
       */
      if (ofc.isInFShopNumber(shop)) {
        Future(s"""{"Result":{"ResponseStatus":{"IsSuccess":true,"Errors":[],"SuccessEntitys":[{"Id":${gyId.hashCode},"Number":"$gyId","DIndex":"$shop"}],"SuccessMessages":[],"MsgCode":0},"Id":${gyId.hashCode},"Number":"$gyId","NeedReturnData":[{}]}}""")
      } else if (ofc.isInFStockNumber(stock)) {
        Future(s"""{"Result":{"ResponseStatus":{"IsSuccess":true,"Errors":[],"SuccessEntitys":[{"Id":${gyId.hashCode},"Number":"$gyId","DIndex":"$stock"}],"SuccessMessages":[],"MsgCode":0},"Id":${gyId.hashCode},"Number":"$gyId","NeedReturnData":[{}]}}""")
      } else {
        //      val dataModel = argJson(0)
        val jsonAddFLotNumber = Json.toJson(dataModel.transform((__ \ "Model").json.update(
          (__ \ "FAddress").json.update(
            optionWithNull[JsString].map { case x => JsString("广东省广州市天河区") }
          ) andThen (__ \ "FConsignee").json.update(
            optionWithNull[JsString].map { case x => JsString("五羊公司") }
          ) andThen (__ \ "FEntity").json.update(
            of[JsArray].map { case JsArray(arr) => Json.toJson(arr.map(_.transform(
              (__ \ "FExpiryDate").json.update {
                optionWithNull[JsString].map { case x => JsString("1971-01-01 00:00:00"); }
              } andThen (__ \ "FProduceDate").json.update {
                optionWithNull[JsString].map { case x => JsString("1971-01-01 00:00:00"); }
              } andThen (__ \ "FLotNumber").json.update {
                optionWithNull[JsNumber].map { case x => JsNumber(2018); }
              }
            )).map(f => f.asOpt)).as[JsArray]
            }
          ))).asOpt)
        kdPost.webApiSave(Json.arr(jsonAddFLotNumber))
      }
    } catch {
      case e: Exception => logger.error("webapiReturnStockService", e); Future(errorInfo("webapiReturnStockService.Exception", s"${argJson.toString()}"))
    }
  }

  // 管易.退换货单》》销售退货单
  def webapiReturnStockService(argJson: JsValue): Future[String] = {
    //val dataModel = argJson(0)("Model")
    logger.debug(s"webapiReturnStockService argJson: ${argJson.toString}")
    import play.api.libs.json._
    import play.api.libs.json.Reads._
    /**
     * var["FExpiryDate"] = "1971-01-01 00:00:00"
     * var["FLotNumber"] = 2018
     * var["FProduceDate"] = "1971-01-01 00:00:00"
     *
     */
    try {
      val dataModel = if ((argJson \ "data").asOpt[JsValue].isEmpty) {
        val p = (argJson \ "parameters").as[JsArray].value.head
        if (p.isInstanceOf[JsObject]) {
          p("Model")
        } else {
          Json.parse(p.as[String])("Model")
        }
      } else {
        (argJson \ "data").as[JsValue]
      }
      logger.debug(s"webapiReturnStockService dataModel: ${dataModel.toString}")
      val shop = (dataModel \ "FShopNumber").get.as[String]
      val stock = (dataModel \ "FStockNumber").get.as[String]
      val gyId = (dataModel \ "FGYBillNo").get.as[String]

      /**
       * {"Result":{"ResponseStatus":{"IsSuccess":true,"Errors":[],"SuccessEntitys":
       * [{"Id":462180,"Number":"XSTHD2108122202","DIndex":0}],"SuccessMessages":[],
       * "MsgCode":0},"Id":462180,"Number":"XSTHD2108122202","NeedReturnData":[{}]}}
       *
       * {"Result":{"ResponseStatus":{"ErrorCode":500,"IsSuccess":false,"Errors":
       * [{"FieldName":"FThirdBillNo","Message":"管易对接销售退货单单据分录行第三方单据编码存在重复",
       * "DIndex":0}],"SuccessEntitys":[],"SuccessMessages":[],"MsgCode":0},
       * "Id":"","NeedReturnData":[{}]}}
       *
       */
      if (ofc.isInFShopNumber(shop)) {
        Future(
          s"""{"Result":{"ResponseStatus":{"IsSuccess":true,
             |"Errors":[],"SuccessEntitys":[{"Id":${gyId.hashCode},
             |"Number":"$gyId","DIndex":"$shop"}],"SuccessMessages":[],
             |"MsgCode":0},"Id":${gyId.hashCode},"Number":"$gyId",
             |"NeedReturnData":[{}]}}""".stripMargin)
      } else if (ofc.isInFStockNumber(stock)) {
        Future(
          s"""{"Result":{"ResponseStatus":{"IsSuccess":true,
             |"Errors":[],"SuccessEntitys":[{"Id":${gyId.hashCode},
             |"Number":"$gyId","DIndex":"$stock"}],"SuccessMessages":[],
             |"MsgCode":0},"Id":${gyId.hashCode},"Number":"$gyId",
             |"NeedReturnData":[{}]}}""".stripMargin)
      } else { //      val dataModel = argJson(0)
        val ossInfo = OutStockSum(
          id = None,
          ossFDate = Timestamp.valueOf((dataModel \ "FDate").as[String]),
          ossFGYBillNo = dataModel("FGYBillNo").as[String],
          ossFShopNumber = shop,
          ossFStockNumber = stock
        )
        val fentity = dataModel("FEntity").as[JsArray].value
        logger.debug(fentity.toString())
        val feInfo = fentity.map {
          v =>
            OutStockSumFEntity(
              ossFAllAmount = v("FAmount").as[Double],
              ossFAmount = v("FAmount").as[Double],
              ossFDiscount = v("FDiscount").as[Double],
              ossFFeeAmount = v("FFeeAmount").as[Double],
              ossFServiceAmount = 0,
              ossFPrice = v("FPrice").as[Double],
              ossFMaterialNumber = v("FMaterialNumber").as[String],
              ossFQty = v("InQty").as[Double].toInt,
              ossOutStockID = None
            )
        }
        //        sendoss.getXSTHDParamBOS(ossInfo = ossInfo, ossFeRes = feInfo.toSeq)
        val tobPara = Json.arr("SAL_RETURNSTOCK", sendoss.getXSTHDParamBOS(ossInfo = ossInfo, ossFeRes = feInfo.toSeq)) //s"[\"SAL_OUTSTOCK\",${getXSCKDToBParamBOS(ossInfo, ossFeRes)}]"
        //        logger.debug(tobPara.toString())
        //        kdPost.webApiSave(tobPara)
        kdPost2.setKdAppConfig(dcId).save("SAL_RETURNSTOCK", sendoss.getXSTHDParamBOS(ossInfo = ossInfo, ossFeRes = feInfo.toSeq))
          .map { r =>
            logger.debug(s"kdPost2.save(\"SAL_RETURNSTOCK\")=>$r")
            try {
              val res = Json.parse(r)
              if (!(res("Result")("ResponseStatus")("IsSuccess").as[Boolean]) && res("Result")("ResponseStatus")("MsgCode").as[Int] == 11) {
                val err = res("Result")("ResponseStatus")("Errors").as[Array[JsValue]]
                val msg = err(0)("Message").as[String]
                if (msg.startsWith("违反字段唯一性要求：编码唯一。") || msg.startsWith("第三方单据编号")) {
                  """{"Result":{"ResponseStatus":{"ErrorCode":500,"IsSuccess":false,"Errors":
                    |[{"FieldName":"FThirdBillNo","Message":"管易对接销售退货单单据分录行第三方单据编码存在重复",
                    |"DIndex":0}],"SuccessEntitys":[],"SuccessMessages":[],"MsgCode":0},
                    |"Id":"","NeedReturnData":[{}]}}""".stripMargin
                } else {
                  r
                }
              } else {
                r
              }
            } catch {
              case e: Exception => {
                logger.info("SendOutStockSum Json.parse Exception:", e);
                r
              }
            }
          }
      }
    } catch {
      case e: Exception => logger.error("webapiReturnStockService", e); Future(errorInfo("webapiReturnStockService.Exception", s"${argJson.toString()}"))
    }
  }

  //,#管易.采购入库单》》
  def webapiInstockService(argJson: JsValue): Future[String] = Future(errorInfo("webapiInstockService", s"${argJson.toString()}"))

  //#管易.采购退货出库单》》
  def webapiPurReturnService(argJson: JsValue): Future[String] = Future(errorInfo("webapiPurReturnService", s"${argJson.toString()}"))

  // Other
  def webapiOther(apiUrl: String, argJson: JsValue): Future[String] = {
    val res = kdPost.post(apiUrl, argJson)
    logger.info(s"WebAPI{$apiUrl}:${argJson.toString()}")
    res
  }

  def apiMatch(apiUrl: String, data: JsValue): Future[String] = {
    apiUrl match {
      case "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc" => webapiView(data)
      case "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc" => webapiSave(data)
      case "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.BatchSave.common.kdsvc" => webapiBatchSave(data)
      case "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Submit.common.kdsvc" => webapiSubmit(data)
      case "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Audit.common.kdsvc" => webapiAudit(data)
      case "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.UnAudit.common.kdsvc" => webapiUnAudit(data)
      case "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Delete.common.kdsvc" => webapiDelete(data)
      case "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc" => webapiQuery(data)
      case "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.StatusConvert.common.kdsvc" => webapiStatusConvert(data)
      case "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExcuteOperation.common.kdsvc" => webapiExcuteOperation(data)
      case "Kingdee.K3.SCM.WebApi.ServicesStub.OutStockService.Save.common.kdsvc" => webapiOutStockService(data)
      case "Kingdee.K3.SCM.WebApi.ServicesStub.ReturnStockService.Save.common.kdsvc" => webapiReturnStockService(data)
      case "Kingdee.K3.SCM.WebApi.ServicesStub.InstockService.Save.common.kdsvc" => webapiInstockService(data)
      case "Kingdee.K3.SCM.WebApi.ServicesStub.PurReturnService.Save.common.kdsvc" => webapiPurReturnService(data)
      case "Kingdee.K3.SCM.WebApi.ServicesStub.UpdateStockService.Save.common.kdsvc" => updateStock(data)
      case _ => webapiOther(apiUrl, data)
    }
  }

  def test(s: String) = kdPost2.setKdAppConfig(s).test(s)

  def updateStock(data: JsValue) = {
    val kdModelEntity = (data \ "ITEM_LIST").as[JsArray].value.map(
      j =>
        KingdeeUpdateModelEntity(
          sId = (j \ "Sid").as[Int],
          qty = (j \ "qty").as[Float],
          lot = (j \ "lot").asOpt[String].getOrElse("2018"),
          srcStock = (j \ "srcStock").asOpt[String].getOrElse(""),
          desStock = (j \ "desStock").asOpt[String].getOrElse("")
        )
    )
    val kdModel = KingdeeUpdateModel(
      fid = (data \ "Fid").as[Int],
      billNo = (data \ "DOC_NO").as[String],
      orderType = (data \ "DOC_TYPE").as[String],
      date = (data \ "Fdate").as[String],
      fEntity = kdModelEntity.toSeq
    )

    val billNo = if (kdModel.billNo.isEmpty) "" else s""""FBillNo":"${kdModel.billNo}","""
    lazy val kd = kdPost2.setKdAppConfig(dcId)
    lazy val para = (modelEntity: String, fe: Seq[String]) =>
      s"""{
         | "Creator":"","NeedUpDateFields":[],"NeedReturnFields":[],
         | "IsDeleteEntry":"true",
         | "InterationFlags":"STK_InvCheckResult",
         | "IsAutoSubmitAndAudit":"true",
         | "Model": {
         |   "FID": ${kdModel.fid},${billNo}
         |   "FDate":"${kdModel.date}",
         |   "$modelEntity":[${fe.mkString(",")}]
         | }
         |}""".stripMargin
    kdModel.orderType match {
      // 销售出库
      case "SAL_OUTSTOCK" | "XSCK" => kd.save(
        "SAL_OUTSTOCK",
        para(
          "FEntity",
          kdModel.fEntity.map {
            feInfo => {
              s"""{
                 |"FENTRYID": ${feInfo.sId},
                 |"FRealQty": ${feInfo.qty},
                 |"FLot": {"FNumber": "${feInfo.lot}"}
                 |}
                 |""".stripMargin
            }
          }
        )
      )

      // 销售退货
      case "SAL_RETURNSTOCK" | "XSTH" => kd.save(
        "SAL_RETURNSTOCK",
        para(
          "FEntity",
          kdModel.fEntity.map {
            feInfo => {
              s"""{
                 |"FENTRYID": ${feInfo.sId},
                 |"FRealQty": ${feInfo.qty},
                 |"FLot": {"FNumber": "${feInfo.lot}"}
                 |}
                 |""".stripMargin
            }
          }
        )
      )

      // 采购入库
      case "STK_InStock" | "CGRK" => kd.save(
        "STK_InStock",
        para(
          "FInStockEntry",
          kdModel.fEntity.map {
            feInfo => {
              s"""{
                 |"FEntryID": ${feInfo.sId},
                 |"FRealQty": ${feInfo.qty},
                 |"FLot": {"FNumber": "${feInfo.lot}"}
                 |}
                 |""".stripMargin
            }
          }
        )
      )

      // 采购退料
      case "PUR_MRB" | "CGTL" => kd.save(
        "PUR_MRB",
        para(
          "FPURMRBENTRY",
          kdModel.fEntity.map {
            feInfo => {
              s"""{
                 |"FEntryID": ${feInfo.sId},
                 |"FRMREALQTY": ${feInfo.qty},
                 |"FLot": {"FNumber": "${feInfo.lot}"}
                 |}
                 |""".stripMargin
            }
          }
        )
      )

      // 直接调拨
      case "STK_TransferDirect" | "ZJDB" => kd.save(
        "STK_TransferDirect",
        para(
          "FBillEntry",
          kdModel.fEntity.map {
            feInfo => {
              s"""{
                 |"FEntryID": ${feInfo.sId},
                 |"FQty": ${feInfo.qty},
                 |"FLot": {"FNumber": "${feInfo.lot}"}
                 |}
                 |""".stripMargin
            }
          }))

      // 分步式调出
      case "STK_TRANSFEROUT" | "FBDC" => kd.save(
        "STK_TRANSFEROUT",
        para(
          "FSTKTRSOUTENTRY",
          kdModel.fEntity.map {
            feInfo => {
              s"""{
                 |"FEntryID": ${feInfo.sId},
                 |"FQty": ${feInfo.qty},
                 |"FLOT": {"FNumber": "${feInfo.lot}"}
                 |}
                 |""".stripMargin
            }
          }))

      // 分步式调入
      case "STK_TRANSFERIN" | "FBDR" => kd.save(
        "STK_TRANSFERIN",
        para(
          "FSTKTRSINENTRY",
          kdModel.fEntity.map {
            feInfo => {
              s"""{
                 |"FEntryID": ${feInfo.sId},
                 |"FQty": ${feInfo.qty},
                 |"FLOT": {"FNumber": "${feInfo.lot}"}
                 |}
                 |""".stripMargin
            }
          }))

      // 其他入库
      case "STK_MISCELLANEOUS" | "QTRK" => kd.save(
        "STK_MISCELLANEOUS",
        para(
          "FEntity",
          kdModel.fEntity.map {
            feInfo => {
              s"""{
                 |"FEntryID": ${feInfo.sId},
                 |"FQty": ${feInfo.qty},
                 |"FLOT": {"FNumber": "${feInfo.lot}"}
                 |}
                 |""".stripMargin
            }
          }
        )
      )

      // 其他出库
      case "STK_MisDelivery" | "QTCK" => kd.save(
        "STK_MisDelivery",
        para("FEntity",
          kdModel.fEntity.map {
            feInfo => {
              s"""{
                 |"FEntryID": ${feInfo.sId},
                 |"FQty": ${feInfo.qty},
                 |"FLot": {"FNumber":"${feInfo.lot}"}
                 |}
                 |""".stripMargin
            }
          }
        )
      )

      // 其他
      case _ => kd.save(
        kdModel.orderType,
        para(
          "FEntity",
          kdModel.fEntity.map {
            feInfo => {
              s"""{
                 |"FEntryID": ${feInfo.sId},
                 |"FQty": ${feInfo.qty},
                 |"FLot": {"FNumber":"${feInfo.lot}"}
                 |}
                 |""".stripMargin
            }
          }
        )
      )

    }

  }


}

case class KingdeeUpdateModelEntity(sId: Int, qty: Float, lot: String = "2018", srcStock: String = "", desStock: String = "")

case class KingdeeUpdateModel(fid: Int, billNo: String = "", orderType: String, date: String, fEntity: Seq[KingdeeUpdateModelEntity])
